package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.qiniu.common.QiniuException;
import com.woniu.entity.Constant;
import com.woniu.entity.Result;
import com.woniu.util.QiNiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/upload")
@Api(tags = "图片上传管理")
@Slf4j
public class UploadController extends BaseController{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取上传图片的原名称
        String originalFilename = file.getOriginalFilename();
        // 2. 拼接新的图片名称
        String uuid = UUID.randomUUID().toString();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = uuid + substring;
        filename = filename.replaceAll("-", "");
        // 3. 调用图片上传的工具类
        QiNiuUploadUtils.uploadFile(file.getBytes(), filename);
        // 上传图片成功之后，需要将图片名称保存redis指定的key中
        stringRedisTemplate.opsForSet().add(Constant.REDIS_ALL_UPLOAD_IMAGE, filename);
        // 4. 返回数据
        return toDataResult(filename);
    }

    @ApiOperation("删除图片")
    @DeleteMapping("/{filename}")
    public Result delete(@PathVariable String filename) throws QiniuException {
        QiNiuUploadUtils.deleteFile(filename);
        return success();
    }

}
